﻿using System;
using System.Collections;
using UnityEngine;

//[RequireComponent(typeof(AudioSource))]
public class MicroManager : MonoSingleton<MicroManager>
{
    private const int HEADER_SIZE = 44;
    private const int RECORD_TIME = 1000;
    private const float VOLUME_UPDATE_INTERVAL = 0.3f;
    private const float VOLUME_RATE = 5f;

    private bool bRecord = false;

    private AudioSource mSource;
    private AudioClip mClip;

    private float _Volume;
    public float Volume
    {
        get
        {
            if (Application.isEditor && Input.GetKey(KeyCode.Space))
                return 1;
            return _Volume;
        }
    }

    private float intervalAddTime = 0;

    protected override void Awake()
    {
        base.Awake();
        mSource = gameObject.AddComponentEx<AudioSource>();
    }

    void Start()
    {
        if (Microphone.devices.Length == 0)
        {
            Debug.LogError("Can't find the devices");
        }
    }

    void Update()
    {
        if (!bRecord)
            return;

        intervalAddTime += Time.deltaTime;
        if (intervalAddTime > VOLUME_UPDATE_INTERVAL)
        {
            intervalAddTime = 0;
            _Volume = GetLevelMax() * VOLUME_RATE;
        }

    }

    protected override void OnDestroy()
    {
        base.OnDestroy();
        StopRecord();
    }

    public void StartRecord()
    {
        StopRecord();
        StartMicroRecord();
        //StartCoroutine(StartMicroRecord());
    }

    public void StopRecord()
    {
        mSource.Stop();
        StopMicroRecord();
    }

    private void StartMicroRecord()
    {
        if (Microphone.devices.Length == 0)
        {
            Debug.Log("No Record Device!");
            //yield break;
            return;
        }

        bRecord = true;
        mClip = Microphone.Start(Microphone.devices[0], false, 1000, 44100);
        mSource.clip = mClip;
        mSource.Play();
        Debug.LogWarning("StartMicroRecord");
    }

    private void StopMicroRecord()
    {
        bRecord = false;
        if (Microphone.devices.Length == 0)
        {
            Debug.Log("No Record Device!");
            return;
        }
        if (!Microphone.IsRecording(null))
        {
            return;
        }
        Microphone.End(null);
        Debug.LogWarning("StopMicroRecord");
    }

    public byte[] GetClipData()
    {
        if (mSource.clip == null)
        {
            Debug.Log("GetClipData audio.clip is null");
            return null;
        }
        float[] array = new float[mSource.clip.samples];
        mSource.clip.GetData(array, 0);
        byte[] array2 = new byte[array.Length * 2];
        int num = 32767;
        for (int i = 0; i < array.Length; i++)
        {
            short num2 = (short)(array[i] * (float)num);
            byte[] bytes = BitConverter.GetBytes(num2);
            array2[i * 2] = bytes[0];
            array2[i * 2 + 1] = bytes[1];
        }
        if (array2 == null || array2.Length <= 0)
        {
            Debug.Log("GetClipData intData is null");
            return null;
        }
        return array2;
    }

    public float GetLevelMax()
    {
        if (mClip == null)
            return 0;
        // 采样数
        int sampleSize = 128;
        float[] samples = new float[sampleSize];
        int startPosition = Microphone.GetPosition(null) - (sampleSize + 1);
        //Debug.Log(startPosition);
        if (startPosition < 0)
            startPosition = 0;
        // 得到数据
        mClip.GetData(samples, startPosition);

        // Getting a peak on the last 128 samples
        float levelMax = 0;
        for (int i = 0; i < sampleSize; ++i)
        {
            float wavePeak = samples[i];
            if (levelMax < wavePeak)
                levelMax = wavePeak;
        }

        return levelMax;
    }
}
